Web 应用开发教程
1. Python 简介和特性
Python 是一种高级编程语言,以其简洁易读的语法和强大的功能而闻名。它广泛应用于Web开发、数据分析、人工智能等领域。
1.1 Python 特性
- 易读性:Python 代码通常比其他语言更接近自然语言。
- 跨平台:Python 可以在多种操作系统上运行。
- 丰富的库:Python 拥有大量的标准库和第三方库,支持各种应用开发。
1.2 环境搭建
1.2.1 安装 Python
- 访问 Python 官方网站 下载最新版本的 Python。
- 安装过程中确保勾选“Add Python to PATH”选项。
1.2.2 IDE 选择
推荐使用以下 IDE:
- PyCharm:功能强大,适合大型项目。
- VS Code:轻量级,插件丰富。
- Jupyter Notebook:适合数据分析和教学。
2. 第一个 Python 程序
print("Hello, World!")
2.1 解释
print是一个内置函数,用于输出内容到控制台。"Hello, World!"是一个字符串,用双引号包裹。
3. 变量和数据类型
3.1 变量
变量是存储数据的容器。
name = "Alice"
age = 25
3.2 数据类型
- 字符串:
str,如"Hello"。 - 整数:
int,如25。 - 浮点数:
float,如3.14。 - 布尔值:
bool,如True或False。
4. 基本运算符
4.1 算术运算符
+:加法-:减法*:乘法/:除法%:取余
a = 10
b = 3
print(a + b) # 输出: 13
print(a % b) # 输出: 1
4.2 比较运算符
==:等于!=:不等于>:大于<:小于
print(a > b) # 输出: True
5. 条件语句
5.1 if 语句
if a > b:
print("a is greater than b")
5.2 elif 语句
if a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
5.3 else 语句
if a > b:
print("a is greater than b")
else:
print("a is not greater than b")
6. 循环
6.1 for 循环
for i in range(5):
print(i)
6.2 while 循环
i = 0
while i < 5:
print(i)
i += 1
7. 异常处理
7.1 try-except 语句
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
8. 列表和元组
8.1 列表
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 输出: apple
8.2 元组
point = (10, 20)
print(point[1]) # 输出: 20
9. 字典和集合
9.1 字典
person = {"name": "Alice", "age": 25}
print(person["name"]) # 输出: Alice
9.2 集合
unique_numbers = {1, 2, 3, 4, 4}
print(unique_numbers) # 输出: {1, 2, 3, 4}
10. 字符串操作
10.1 字符串拼接
first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name) # 输出: Alice Smith
10.2 字符串格式化
age = 25
message = f"My name is {first_name} and I am {age} years old."
print(message) # 输出: My name is Alice and I am 25 years old.
11. 函数定义和调用
11.1 定义函数
def greet(name):
return f"Hello, {name}!"
11.2 调用函数
print(greet("Alice")) # 输出: Hello, Alice!
12. 参数和返回值
12.1 参数
def add(a, b):
return a + b
12.2 返回值
result = add(10, 20)
print(result) # 输出: 30
13. 模块导入和使用
13.1 导入模块
import math
13.2 使用模块
print(math.sqrt(16)) # 输出: 4.0
14. 包管理 (pip)
14.1 安装包
pip install requests
14.2 使用包
import requests
response = requests.get("https://api.example.com")
print(response.status_code)
15. 类和对象
15.1 定义类
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
15.2 创建对象
my_dog = Dog("Buddy")
print(my_dog.bark()) # 输出: Buddy says woof!
16. 继承和多态
16.1 继承
class Animal:
def speak(self):
return "Animal sound"
class Dog(Animal):
def speak(self):
return "Woof!"
16.2 多态
def animal_sound(animal):
print(animal.speak())
animal_sound(Animal()) # 输出: Animal sound
animal_sound(Dog()) # 输出: Woof!
17. 封装和抽象
17.1 封装
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
17.2 抽象
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
18. 读写文本文件
18.1 写文件
with open("example.txt", "w") as file:
file.write("Hello, World!")
18.2 读文件
with open("example.txt", "r") as file:
content = file.read()
print(content) # 输出: Hello, World!
19. 处理 CSV, JSON 数据
19.1 CSV
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
19.2 JSON
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
20. 文件系统操作
20.1 创建目录
import os
os.mkdir("new_directory")
20.2 列出文件
for file in os.listdir("."):
print(file)
21. 生成器和迭代器
21.1 生成器
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
for number in count_up_to(5):
print(number)
21.2 迭代器
class MyIterator:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.limit:
self.current += 1
return self.current - 1
else:
raise StopIteration
for number in MyIterator(5):
print(number)
22. 装饰器
22.1 定义装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
23. 上下文管理器
23.1 使用 with 语句
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with FileManager("example.txt", "w") as file:
file.write("Hello, World!")
24. 多线程和并发
24.1 多线程
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
25. datetime 和 time 模块
25.1 datetime
from datetime import datetime
now = datetime.now()
print(now) # 输出当前日期和时间
25.2 time
import time
time.sleep(2) # 暂停2秒
26. os 和 sys 模块
26.1 os
import os
print(os.getcwd()) # 输出当前工作目录
26.2 sys
import sys
print(sys.version) # 输出Python版本
27. re 模块 (正则表达式)
27.1 匹配字符串
import re
pattern = r"\d+"
text = "There are 123 apples."
match = re.search(pattern, text)
print(match.group()) # 输出: 123
28. collections 模块
28.1 Counter
from collections import Counter
fruits = ["apple", "banana", "apple", "cherry", "banana"]
counter = Counter(fruits)
print(counter) # 输出: Counter({'apple': 2, 'banana': 2, 'cherry': 1})
29. NumPy 和 Pandas (数据分析)
29.1 NumPy
import numpy as np
array = np.array([1, 2, 3, 4, 5])
print(array) # 输出: [1 2 3 4 5]
29.2 Pandas
import pandas as pd
data = {"name": ["Alice", "Bob"], "age": [25, 30]}
df = pd.DataFrame(data)
print(df)
30. Matplotlib (数据可视化)
30.1 绘制折线图
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()
31. Requests (HTTP 请求)
31.1 发送 GET 请求
import requests
response = requests.get("https://api.example.com")
print(response.status_code)
32. Flask/Django (Web 开发)
32.1 Flask 入门
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True)
32.2 Django 入门
django-admin startproject myproject
cd myproject
python manage.py runserver
33. SQLite 基础
33.1 创建数据库
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
conn.commit()
conn.close()
34. MySQL/PostgreSQL 连接
34.1 MySQL
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor:
print(row)
conn.close()
34.2 PostgreSQL
import psycopg2
conn = psycopg2.connect(
host="localhost",
database="mydatabase",
user="postgres",
password="password"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor:
print(row)
conn.close()
35. ORM 使用 (SQLAlchemy)
35.1 定义模型
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
new_user = User(name="Alice", age=25)
session.add(new_user)
session.commit()
36. HTML, CSS 基础
36.1 HTML
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, World!</h1>
</body